<?php

namespace app\admin\model;

use EasyWeChat\Factory;
use think\Cache;
use think\Env;
use think\Model;
use fast\Random;

class Admin extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    public static $app;
    // 追加属性
    protected $append = [
        'gender_text',
        'isleader_text',
        'department_text',
        'delete_status_text'
    ];

    public function initialize()
    {
        self::$app = Factory::work(Admin::config());
    }

    public function wageslist()
    {
        return $this->belongsTo('Wageslist', 'userid', 'userid', [], 'LEFT')->setEagerlyType(0);
    }
   
    /**
     * 重置用户密码
     * @author baiyouwen
     */
    public function resetPassword($uid, $NewPassword)
    {
        $passwd = $this->encryptPassword($NewPassword);
        $ret = $this->where(['id' => $uid])->update(['password' => $passwd]);
        return $ret;
    }

    // 密码加密
    protected function encryptPassword($password, $salt = '', $encrypt = 'md5')
    {
        return $encrypt($password . $salt);
    }

    public function getGenderList()
    {
        return ['1' => __('男'),'2' => __('女')];
    }
    public function getZhengshiList()
    {
        return ['1' => __('否'),'2' => __('是')];
    }
    public function getDeleteStatusList()
    {
        return ['0' => __('管理员'),'1' => __('已激活'),'2' => __('已禁用'),'4'=>__('未激活')];
    }

    public function getDepartmentList()
    {
        return array_column(collection(AuthDepartment::field('id,name,delete_status')->select())->toArray(), 'name','id');
    }

    public function getIsleaderList()
    {
        return ['1' => __('Isleader 1'),'0' => __('Isleader 0')];
    }

    public function getDeleteStatusTextAttr($value,$data)
    {
        $value = $value ? $value : $data['delete_status'];
        $list = $this->getDeleteStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }
    public function getDepartmentTextAttr($value, $data)
    {
        $value = $value ? $value : $data['department'];
        $list = $this->getDepartmentList();
        $arr = explode(',',$value);

        foreach ($arr as $value)
        {
            $str[] = $list[$value] ?? '';
        }
        $str  = implode(',', $str);
        return  $str;
    }

    public function getGenderTextAttr($value, $data)
    {
        $value = $value ? $value : $data['gender'];
        $list = $this->getGenderList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getIsleaderTextAttr($value, $data)
    {
        $value = $value ? $value : $data['isleader'];
        $list = $this->getIsleaderList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 添加到用户企业微信
     * @param $data
     * @return mixed
     */
    public static function createAdmin($data)
    {
        return self::$app->user->create($data);
    }

    /**
     * 修改企业微信信息
     * @param $id
     * @param $data
     * @return mixed
     */
    public static function updateAdmin($id,$data)
    {
        return self::$app->user->update($id,$data);
    }

    /**
     * 删除用户  可以删除多个 数组
     * @param $id
     * @return mixed
     */
    public static function deleteAdmin($id)
    {
        return self::$app->user->delete($id);
    }

    /**
     * 获取所有部门成员
     * @return mixed
     */
    public static function listAdmin()
    {
        return self::$app->user->getDetailedDepartmentUsers(1, true);
    }

    /**
     * 微信同步更新用户
     * @param $userId
     * @param $data
     */
    public static function updateUser($userId,$data)
    {
        //销毁没用的字段
        $data = Admin::unsetAttr($data);
        Admin::update($data,['userid'=>$userId],array_keys($data));
    }

    /**
     *  微信同步创建用户  默认密码123456
     * @param $data
     */
    public static function createUser($data)
    {
        $data = Admin::unsetAttr($data);
        $data['salt'] = Random::alnum();
        $data['password'] = md5(md5('123456') . $data['salt']);
        Admin::create($data);
    }

    /**
     *  微信同步删除用户
     * @param $userId
     */
    public static function deleteUser($userId)
    {
        Admin::update(['delete_status'=>2],['userid'=>$userId],['delete_status']);
    }

    public static function workAdd($data = [])
    {
        return self::$app ->user->create($data);
    }

    public static function config()
    {
        $config = [
            'corp_id' => Env::get('user.corp_id'),
            'secret'   => Env::get('user.secret'),
            'token'=>Env::get('user.token'),
            'aes_key'=>Env::get('user.aes_key'),
            'response_type' => Env::get('user.response_type'),
            'log' => [
                'level' => Env::get('user.level'),
                'file' => __DIR__.Env::get('user.file'),
            ],
        ];
        return $config;
    }

    public static function UserConfig()
    {
        $config = [
            'agent_id' => Env::get('myAccount.agent_id'),
            'corp_id' => Env::get('user.corp_id'),
            'secret'   => Env::get('myAccount.secret'),
            'response_type' => Env::get('myAccount.response_type'),
            'log' => [
                'level' => Env::get('myAccount.level'),
                'file' => __DIR__.Env::get('myAccount.file'),
            ],
            'oauth'=> [
                'scopes'=> Env::get('myAccount.scopes'),
                'callback' => Env::get('myAccount.callback')
            ]
        ];
        return $config;
    }

    /*
     * 销毁多余的字段
     */
    public static function unsetAttr($data)
    {
        unset($data['ToUserName'],$data['FromUserName'],$data['CreateTime'],$data['MsgType'],$data['ChangeType'],$data['Event']);
        $data = array_change_key_case($data);
        if(isset($data['newuserid']))
        {
            $data['userid'] = $data['newuserid'];
            unset($data['newuserid']);
        }
        if(isset($data['englishname']))
        {
            $data['nickname'] = $data['englishname'];
        }
        if(isset($data['name']))
        {
            $data['username'] = $data['name'];
            unset($data['name']);
        }
        if(isset($data['adduseritems']))
        {
            unset($data['adduseritems']);
        }
        if(isset($data['extattr']['Item'])) {
            $data['extattr']['Item'] = array_column($data['extattr']['Item'],'Value','Name');
            if(isset($data['extattr']['Item']['身份证号'])){
                $data['id_number'] = $data['extattr']['Item']['身份证号'];
            }
            if(isset($data['extattr']['Item']['银行卡号'])){
                $data['card_number'] = $data['extattr']['Item']['银行卡号'];
            }
            unset($data['extattr']);
        }
        //Gender  1表示男性，2表示女性
        if(isset($data['status']))
        {
            //1=激活或关注， 2=禁用， 4=未激活
            $status = [1 =>'Status1',2 =>'Status2',4 =>'Status4'];
            $data['status'] = $status[$data['status']];
        }

        return $data;
    }


    /**
     * 同步更新权限的数据
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function groupUpdate()
    {
        $data = AuthGroup::getAllTab();
        $group = [['uid'=>1,'group_id'=>1,'userid'=>1]];
        foreach ($data as $value)
        {
            $res = AuthGroup::getTab($value);
            foreach ($res['userlist'] as $val)
            {
                $admin = Admin::where('userid',$val['userid'])->field('id')->find();
                $group[] = ['uid'=>$admin->id,'group_id'=>$value,'userid'=>$val['userid']];
            }
        }
        return $group;
    }

    /**
     * 获取姓名
     * @param $userId
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function userName($userId)
    {
        if(!$userlist = Cache::get('USERLIST'))
        {
            $userlist = collection(Admin::field("userid,username,gender,isleader,department,delete_status")->select())->toArray();
            $userlist = array_column($userlist,null,'userid');
            Cache::set('USERLIST',$userlist,604800);//有效期一个星期
        }
        return $userlist[$userId]['username'];
    }

    public static function getId($name)
    {
        $ret = self::get(['username'=>$name])->toArray();
        return $ret['userid'];
    }
}
